package top.codef.money;

import java.io.IOException;

import javax.money.MonetaryAmount;
import javax.money.format.AmountFormatContext;
import javax.money.format.MonetaryParseException;

import top.codef.money.interfaces.MercuryMonetaryAmountFormat;
import top.codef.money.interfaces.MoneyPrinter;

public class MercuryMonetaryFormat implements MercuryMonetaryAmountFormat {

	/**
	 * The current {@link javax.money.format.AmountFormatContext}, never null.
	 */
	private AmountFormatContext amountFormatContext;

	private final MoneyPrinter printer;

	private final MercuryMoneyParserDelegate parserDelegate;

	public MercuryMonetaryFormat(AmountFormatContext amountFormatContext, MoneyPrinter printer,
			MercuryMoneyParserDelegate parserDelegate) {
		this.amountFormatContext = amountFormatContext;
		this.printer = printer;
		this.parserDelegate = parserDelegate;
	}

	public AmountFormatContext getAmountFormatContext() {
		return amountFormatContext;
	}

	public MoneyPrinter getPrinter() {
		return printer;
	}

	@Override
	public String queryFrom(MonetaryAmount amount) {
		return format(amount);
	}

	@Override
	public AmountFormatContext getContext() {
		return amountFormatContext;
	}

	@Override
	public void print(Appendable appendable, MonetaryAmount amount) throws IOException {
		appendable.append(printer.print(amount));
	}

	@Override
	public MonetaryAmount parse(CharSequence text) throws MonetaryParseException {
		MonetaryAmount monetaryAmount = text == null ? null : parserDelegate.parse(text.toString());
		return monetaryAmount;
	}

	@Override
	public <T extends MonetaryAmount> T parse(CharSequence text, Class<? extends MonetaryAmount> clazz) {
		T t = parserDelegate.parse(text.toString(), clazz);
		return t;
	}
}
